package org.freez4.spring.resource;

import org.freez4.spring.resource.util.ResourceUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.Resource;

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;


/**
 * 注入 {@link Resource} 对象示例
 *
 * @author 阿坤同学
 * @date 2024/1/19 10:19 AM
 * @see Resource
 * @see AnnotationConfigApplicationContext
 * @see Value
 */
public class InjectingResourceDemo implements InitializingBean {

    public static final Logger logger = Logger.getLogger(InjectingResourceDemo.class.getName());

    @Value("classpath:/META-INF/default.properties")
    private Resource defaultPropertiesResource;

    @Value("classpath*:/META-INF/*.properties")
    private Resource[] propertiesResources;

    @Value("${user.dir}")
    private String currentProjectRootPath;

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.log(Level.INFO, () -> "defaultPropertiesResource: " + ResourceUtils.getContent(defaultPropertiesResource));
        logger.info("==================================================");
        Stream.of(propertiesResources).map(ResourceUtils::getContent).forEach(logger::info);
        logger.info("==================================================");
        logger.log(Level.INFO, () -> "currentProjectRootPath: " + currentProjectRootPath);
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册当前类作为 Configuration Class
        context.register(InjectingResourceDemo.class);
        // 启动 Spring 应用上下文
        context.refresh();
        // 关闭 Spring 应用上下文
        context.close();
    }
}